<template>
  <div style="height: 100vh">
    <div
      style="
        min-height: 100%;
        width: 100%;
        padding-bottom: 70px;
        background: #efefef;
        padding-left: 4px;
        padding-right: 4px;
      "
    >
      <Waterfall
        ref="waterfall"
        :list="list"
        :row-key="options.rowKey"
        :gutter="options.gutter"
        :has-around-gutter="options.hasAroundGutter"
        :width="options.width"
        :breakpoints="options.breakpoints"
        :img-selector="options.imgSelector"
        :background-color="options.backgroundColor"
        :animation-effect="options.animationEffect"
        :animation-duration="options.animationDuration"
        :animation-delay="options.animationDelay"
        :animation-cancel="options.animationCancel"
        :lazyload="options.lazyload"
        :load-props="options.loadProps"
        :align="options.align"
        @afterRender="afterRender"
      >
        <template #default="{ item }">
          <div @click.stop="handleClick(item)">
            <div
              class="overflow-hidden"
              v-if="
                item.article_images[0].includes('.jpg') ||
                item.article_images[0].includes('.png') ||
                item.article_images[0].includes('.jpeg') ||
                item.article_images[0].includes('.gif')
              "
            >
              <LazyImg
                :url="item.article_images[0]"
                title="title"
                :alt="item.name"
                class="cursor-pointer transition-all duration-300 ease-linear group-hover:scale-105"
                @load="imageLoad"
                @error="imageError"
                @success="imageSuccess"
              />
              <div class="fall-title">
                <h2 class="ellipsis">
                  {{ item.article_title }}
                </h2>
                <div class="flex items-center mt-10">
                  <div class="flex items-center flex-1 cont-title">
                    <LazyImg
                      :url="item.avatarUrl || `${imgUrl}/image/mine/default-user.png`"
                      title="title"
                      :alt="item.name"
                      class="cursor-pointer transition-all duration-300 ease-linear group-hover:scale-105"
                      @load="imageLoad"
                      @error="imageError"
                      @success="imageSuccess"
                    />
                    <div class="nickname">{{ item.nickName }}</div>
                  </div>
                  <div class="flex items-center">
                    <i class="iconfont icon-heart f-desc"></i>
                    <p class="ticket">{{ item.ticket }}</p>
                  </div>
                </div>
              </div>
            </div>
            <div v-else>
              <div class="video-wrapper">
                <!-- <video ref="videoPlayer" class="video" width="100%">
                  <source :src="item.article_images[0]" type="video/mp4" />
                </video> -->

                <video
                  ref="videoPlayer"
                  class="video-js vjs-default-skin video"
                  preload="auto"
                  :show-center-play-btn="false"
                  :enable-play-gesture="false"
                  :enable-progress-gesture="false"
                  :poster="`${item.article_images[0]}?vframe/jpg/offset/0`"
                >
                  <!-- 可以在这里插入source标签以指定你的视频源 -->
                  <source :src="`${item.article_images[0]}?vframe/jpg/offset/0`" type="video/mp4" />
                </video>
                <i class="iconfont icon-bofang"></i>
              </div>
              <div class="fall-title">
                <h2 class="ellipsis">
                  {{ item.article_title }}
                </h2>
                <div class="flex items-center mt-10">
                  <div class="flex items-center flex-1 cont-title">
                    <LazyImg
                      :url="item.avatarUrl || `${imgUrl}/image/mine/default-user.png`"
                      title="title"
                      :alt="item.name"
                      class="cursor-pointer transition-all duration-300 ease-linear group-hover:scale-105"
                      @load="imageLoad"
                      @error="imageError"
                      @success="imageSuccess"
                    />
                    <div class="nickname">{{ item.nickName }}</div>
                  </div>
                  <div class="flex items-center">
                    <i class="iconfont icon-heart f-desc"></i>
                    <p class="ticket">{{ item.ticket }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </Waterfall>

      <div class="more">
        <p @click="handleLoadMore">
          {{ moretext }}
        </p>
      </div>
    </div>
    <div class="tabbar">
      <div class="tab-list">
        <div
          class="item"
          v-for="(item, index) in TabBarList"
          @click="onTabBar(item, index)"
          :style="{ marginTop: index == 2 ? '-22px' : '0px' }"
          :key="index"
        >
          <img
            :src="item.acImg"
            v-show="index == 2"
            :style="{
              width: index == 2 ? '40px' : '40px',
              borderRadius: index == 2 ? '8px' : '0px',
            }"
          />
          <span :class="{ action: tabBarShow == index }" v-show="index !== 2">{{ item.name }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { LazyImg, Waterfall } from '../lib/index'
// import { LazyImg, Waterfall } from 'vue-waterfall-plugin-next'
//   import 'vue-waterfall-plugin-next/dist/style.css'
import type { ViewCard } from '../lib/types/waterfall'
import { getList, deleteNote } from '../api/api'
import loadingPng from '../assets/loading.png'
import error from '../assets/error.png'
import issue from '../assets/issue.png'
import router from '@/router'
import { useRoute } from 'vue-router'
import { useToken } from '../stores/user'
import wx from 'weixin-js-sdk'
import 'video.js/dist/video-js.css'

const useTokenStore = useToken()
const route = useRoute()

const imgUrl = 'https://wofo.shuchen.fun/static/scnc'
const options = reactive({
  // 唯一key值
  rowKey: 'id',
  // 卡片之间的间隙
  gutter: 10,
  // 是否有周围的gutter
  hasAroundGutter: true,
  // 卡片在PC上的宽度
  width: 320,
  // 自定义行显示个数，主要用于对移动端的适配
  breakpoints: {
    1200: {
      // 当屏幕宽度小于等于1200
      rowPerView: 2,
    },
    800: {
      // 当屏幕宽度小于等于800
      rowPerView: 2,
    },
    500: {
      // 当屏幕宽度小于等于500
      rowPerView: 2,
    },
  },
  // 动画效果
  animationEffect: 'animate__fadeInUp',
  // 动画时间
  animationDuration: 1000,
  // 动画延迟
  animationDelay: 300,
  animationCancel: false,
  // 背景色
  backgroundColor: '#2C2E3A',
  // imgSelector
  imgSelector: 'src.original',
  // 加载配置
  loadProps: {
    loadingPng,
    error,
    // ratioCalculator: (width: number, height: number) => {
    //   // 我设置了最小宽高比
    //   const minRatio = 3 / 4
    //   const maxRatio = 4 / 3
    //   return Math.random() > 0.5 ? minRatio : maxRatio
    // },
  },
  // 是否懒加载
  lazyload: true,
  align: 'center',
})

// 列表
const list = ref<ViewCard[]>([])
const page = ref(1)
const loading = ref(true)
const tabBarShow = ref(3)
const moretext = ref('加载更多')

const userInfo = ref({
  id: '',
  type: '',
})

const TabBarList = [
  {
    index: 0,
    name: '睡FO',
    acImg: issue,
  },
  {
    index: 1,
    name: '农场',
    acImg: issue,
  },
  {
    index: 2,
    name: '发布',
    acImg: issue,
  },
  {
    index: 3,
    name: '笔记',
    acImg: issue,
  },
  {
    index: 4,
    name: '精灵',
    acImg: issue,
  },
]
onMounted(() => {
  handleLoadMore()
  // H5获取token const wxobj = {}
  const wxobj: Record<string, string> = {}
  window.location.href.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (wxobj[k] = v))
  console.log(12333, wxobj)
  console.log('thissssss===', route)
  useTokenStore.setToken(wxobj.token)
  if (wxobj.userInfoId) {
    userInfo.value.id = wxobj.userInfoId
    userInfo.value.type = wxobj.type // 0:正常，1:审核中
  }
})

// 加载更多
async function handleLoadMore() {
  try {
    // 删除笔记
    // await deleteNote({ note_id: 36 })
    const res = await getList({
      page: page.value,
    })
    if (userInfo.value.type == '0') {
      list.value.push(...res)
    } else {
      // image
      list.value.push(
        ...res.filter(
          (item) =>
            item.article_images[0].includes('.jpg') ||
            item.article_images[0].includes('.png') ||
            item.article_images[0].includes('.jpeg') ||
            item.article_images[0].includes('.gif'),
        ),
      )
    }
    if (res && res.length == 0) {
      moretext.value = '没有更多了'
      return
    }
    page.value += 1
  } catch (err) {
    console.log(err)
  }
}

// 删除
// function handleDelete(item: ViewCard, index: number) {
//   list.value.splice(index, 1)
// }

function handleClick(item: ViewCard) {
  router.push(`/detail/${item.id}/${userInfo.value.id}`)
}

function imageLoad(url: string) {
  console.log(`${url}: 加载完成`)
}

function imageError(url: string) {
  console.error(`${url}: 加载失败`)
}

function imageSuccess(url: string) {
  console.log(`${url}: 加载成功`)
}

function afterRender() {
  loading.value = false
  // console.log('计算完成')
}
const waterfall = ref(null)
//   function handleRender() {
//     waterfall.value.renderer()
//     // console.log(waterfall.value)
//   }
//   点击tabbar
function onTabBar(item: any, index: number) {
  wx.miniProgram.postMessage({
    data: { index },
  })
  let url = ''
  switch (item.index) {
    case 0:
      url = '/pages/home'
      break
    case 1:
      url = '/pages/shop'
      break
    case 2:
      url = '/pages/public'
      break
    case 4:
      url = '/pages/mine'
      break
  }
  wx.miniProgram.switchTab({
    url: url, // 小程序地址
    success() {
      console.log('question success')
    },
    fail(error) {
      console.log(error)
    },
  })
}
</script>

<style lang="less" scoped>
.fall-title {
  padding: 4px 4px 10px;
}
.ellipsis {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  color: #1c1d1e;
  font-size: 16px;
}
.flex {
  display: flex;
}
.flex-1 {
  flex: 1;
}
.items-center {
  align-items: center;
}
.mt-10 {
  margin-top: 10px;
}
.cont-title {
  ::v-deep(.lazy__box) {
    padding-bottom: 0 !important;
    width: 24px;
    height: 24px;
  }
  ::v-deep(.lazy__resource) {
    width: 24px;
    height: 24px;
  }
  ::v-deep(.lazy__img) {
    border-radius: 50%;
  }
  .nickname {
    margin-left: 4px;
    color: #909399;
  }
}
.iconfont {
  font-size: 14px;
}
.ticket {
  margin-left: 2px;
  color: #909399;
}
.more {
  width: 100%;
  height: 40px;
  p {
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
}
.video-wrapper {
  position: relative;
  .icon-bofang {
    position: absolute;
    left: 10px;
    bottom: 12px;
    font-size: 20px;
    color: #fff;
  }
}
.video {
  width: 100%;
  max-height: 240px;
  border-radius: 10px 10px 0 0;
  object-fit: cover;
}
.tabbar {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  z-index: 2;
  .tab-list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding-bottom: 24px;
    padding-top: 6px;
    background-color: #fff;
  }
  .item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-end;
    width: 20%;
    img {
      width: 40px;
      height: 40px;
      background-color: white;
    }
    span {
      color: #909399;
      font-size: 16px;
    }
    .action {
      background: linear-gradient(to right, #ff934f, #fa6100);
      color: #fff;
      padding: 3px 9px 3px 6px;
      border-radius: 20px;
      font-weight: bold;
      font-size: 16px;
      font-style: oblique;
    }
  }
}
::v-deep(.video-js .vjs-tech) {
  object-fit: cover;
}
</style>
